package com.boomshake.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * 微信API工具类
 *
 * @author BoomShake
 * @date 2024-12-15
 */
@Slf4j
@Component
public class WeChatUtil {

    @Value("${wechat.miniapp.app-id}")
    private String appId;

    @Value("${wechat.miniapp.app-secret}")
    private String appSecret;

    /**
     * 微信小程序登录API地址
     */
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 通过code获取微信用户信息
     *
     * @param code 小程序登录时获取的code
     * @return 微信用户信息
     */
    public WeChatLoginResult getWeChatUserInfo(String code) {
        String url = buildLoginUrl(code);
        
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.info("微信登录API返回: {}", result);
                
                JSONObject jsonObject = JSON.parseObject(result);
                
                // 检查是否有错误
                if (jsonObject.containsKey("errcode")) {
                    Integer errcode = jsonObject.getInteger("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    log.error("微信登录失败: errcode={}, errmsg={}", errcode, errmsg);
                    throw new RuntimeException("微信登录失败: " + errmsg);
                }
                
                WeChatLoginResult loginResult = new WeChatLoginResult();
                loginResult.setOpenid(jsonObject.getString("openid"));
                loginResult.setSessionKey(jsonObject.getString("session_key"));
                loginResult.setUnionid(jsonObject.getString("unionid"));
                
                return loginResult;
            }
        } catch (IOException e) {
            log.error("调用微信登录API异常", e);
            throw new RuntimeException("调用微信API失败", e);
        }
    }

    /**
     * 构建微信登录URL
     *
     * @param code 登录code
     * @return 完整的API URL
     */
    private String buildLoginUrl(String code) {
        try {
            return WX_LOGIN_URL +
                    "?appid=" + URLEncoder.encode(appId, "UTF-8") +
                    "&secret=" + URLEncoder.encode(appSecret, "UTF-8") +
                    "&js_code=" + URLEncoder.encode(code, "UTF-8") +
                    "&grant_type=authorization_code";
        } catch (Exception e) {
            log.error("构建微信登录URL失败", e);
            throw new RuntimeException("构建微信登录URL失败", e);
        }
    }

    /**
     * 微信登录结果
     */
    public static class WeChatLoginResult {
        private String openid;
        private String sessionKey;
        private String unionid;

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }

        public String getSessionKey() {
            return sessionKey;
        }

        public void setSessionKey(String sessionKey) {
            this.sessionKey = sessionKey;
        }

        public String getUnionid() {
            return unionid;
        }

        public void setUnionid(String unionid) {
            this.unionid = unionid;
        }

        @Override
        public String toString() {
            return "WeChatLoginResult{" +
                    "openid='" + openid + '\'' +
                    ", sessionKey='" + sessionKey + '\'' +
                    ", unionid='" + unionid + '\'' +
                    '}';
        }
    }
} 